#include "threadPool.h"

int recvFile(int netfd, char* buf)
{
   // //数据库连接
   // char *mysqlUserName = "root";
   // char *mysqlUserPass = "1234";
   // MYSQL * forCheck = mysqlConnect(mysqlUserName,mysqlUserPass);
   
    char sql[1024];//存储SQL语句的字符串
    int pre_id;//存储查询到的pre_id值


    char bufForFilePath1[1024];
    int lengthForFilePath;
    recvn(netfd,&lengthForFilePath,sizeof(int));
    recvn(netfd,bufForFilePath1,lengthForFilePath);//这里得到客户端传来的path
    printf("the full_file_path received from client is %s\n",bufForFilePath1);

    char bufForFilePath2[1024];
    strcpy(bufForFilePath2,bufForFilePath1);
    printf("the value for bufForFilePath2 is %s\n",bufForFilePath2);


    char preIDresult[1024]={0};//用于存储最终结果的字符串
    int firstTokenFlag =1;
    char *strFromBuf = bufForFilePath1;
    char *arr[100]; //存储切割后的字符串数组
    int i =0; //从下标0开始
    char usernameFromToken[1024];
    char filenameFromToken[1024];

    char *token = strtok(strFromBuf,"/");
    while(token != NULL)
    {
        arr[i++] = token;
        token = strtok(NULL,"/");
    }
    //test for the first token
    printf("i = %d",i);
    printf("the arr[0] is %s\n",arr[0]);
    printf("the arr[%d] is %s\n",0,arr[0]);
    //从这里出来之后arr[0]一定是username

    //test for the last token
    printf("the arr[i-1] is %s\n",arr[i-1]);
    printf("the arr[%d] is %s\n",i,arr[i-1]);
    //arr[i]一定是filename
    strcpy(usernameFromToken,arr[0]);
    strcpy(filenameFromToken,arr[i-1]);
    for(int n=0;n<i-1;n++)
    {
        printf("enter the for loop \n");
        if(firstTokenFlag)
        {
            firstTokenFlag = 0;
        }
        else
        {
            strcat(preIDresult,"/");
        }
        strcat(preIDresult,arr[n]);
        printf("inner check ,current path's pre filepath is %s\n",preIDresult);
    }//从这个for循环出来就代表当前文件的父路径得到了
    //test
    printf("current path's  pre filepath is %s\n",preIDresult);
    //这里出来之后 arr[n]的值就是传进来的字符串中除开filename的值
    //在数据库表中查找arr[n]这个字符串的id,记录下来作为文件下载完成后
    //插入数据库中的pre_id值
    //1)执行SQL查询找pre_id
    char bufForPreID[1024];
    snprintf(bufForPreID, sizeof(bufForPreID), "SELECT * FROM FileTable WHERE path='%s'", preIDresult);
    //char bufForPreID[1024] = "SELECT id FROM FileTable WHERE path = 'preIDresult'";
    //sprintf(sql,"SELECT pre_id FROM FileTable WHERE path ='%s'",preIDresult);
    //if(mysql_query(forCheck,sql))
    //{
    //printf("ERROR:Failed to query dadtabase:%s\n",mysql_error(forCheck));
    //
    //}
    int qret = mysql_query(mysql,bufForPreID);
    if(qret !=0)
    {
        fprintf(stderr,"sql research failed:%s\n",mysql_error(mysql));
        return -1;
    }
    //2)获取查询结果
    MYSQL_RES *result;//用来存储查询结果集
    result = mysql_store_result(mysql);
    if(result ==NULL)
    {
        printf("ERROR: Failed to get query result :%s\n",mysql_error(mysql));
        exit(1);
    }
    //3)处理查询结果，获取pre_id值
    MYSQL_ROW row;  // 存储查询结果的行数据
    row = mysql_fetch_row(result);
    pre_id = atoi(row[0]);
    printf(" value for row0 is %s\n",row[0]);
    printf("value for row0 is %d\n",atoi(row[0]));
    //4)释放查询结果
    mysql_free_result(result);
    //从这里出来可以得到pre_id
    printf("the pre_id is %d\n",pre_id);


    char bufForFileName[1024];
    strcpy(bufForFileName,filenameFromToken);
    //收文件名
    int length;
    recvn(netfd,&length,sizeof(length));
    recvn(netfd,bufForFileName,length);
    //收文件大小
    off_t file_size;
    recvn(netfd,&length,sizeof(length));
    recvn(netfd,&file_size,length);
    printf("the filesize is %ld\n",file_size);
    int fd = open(bufForFileName,O_RDWR|O_CREAT,0666);

    off_t cursize =0;
    off_t slice = file_size/10000;
    off_t lastsize =0;

    while(1)
    {
        char buf[4096]={0};
        recvn(netfd,&length,sizeof(length));
        if(length !=1000)
        {
            printf("the length is %d\n",length);
        }
        if(length == 0)
        {
            break;
        }
        //根据上面收到的length收文件内容
        recvn(netfd,buf,length);
        //将收到buf中的内容通过fd写进刚刚打开的文件流
        write(fd,buf,length);
        cursize += length;
        if(cursize -lastsize > slice)
        {
            printf("%5.2lf%%\r",100.0*cursize/file_size);
            fflush(stdout);
            lastsize = cursize;
        }
    }
    printf("100.00%%\n");
    //到这里说明文件从客户端那边上传成功
    // char bufForDB = "INSERT INTO FileTable VALUES()"
    //1)函数第二个参数是”username/filename“
    //2)strtok拿到字符串中一个/前的值作为username和最后一个/后的值作为filename
    //3)strtok拿到字符串中最后一个/前的所有字符串去数据库查找对应path的id作为现在要插入的pre_id
    //type : f
    //path: 第二个参数
    //md5值,文件内容经过md5函数计算后返回得到
    //tomb =0 
    //计算md5值
    char bufForMD5[1024]={0};
    Compute_file_md5(filenameFromToken,bufForMD5);
    printf("the MD5 value been calculated out is %s\n",bufForMD5);
    //todo SQL语句进行插入

    //文件上传成功后执行SQL插入
    char bufForInsertDB[1024];
    snprintf(bufForInsertDB,sizeof(bufForInsertDB),
             "INSERT INTO FileTable (filename,username,pre_id,type,path,md5,tomb) VALUES ('%s','%s','%d','f','%s','%s',0)",filenameFromToken,usernameFromToken,pre_id,bufForFilePath2,bufForMD5);

    int qret2 = mysql_query(mysql,bufForInsertDB);
    if(qret2 !=0)
    {
        fprintf(stderr,"sql error: %s\n",mysql_error(mysql));
       // bzero(&train);
    }
    close(fd);

    return 0;

}

